package top.lixunda.common.validate.validate;

import top.lixunda.common.validate.annotation.XumDateTimeFormat;
import top.lixunda.common.validate.core.ValidateError;
import top.lixunda.common.validate.exception.XumValidException;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.regex.Pattern;

/**
 * @author Xumda
 * @version time:2019/12/9 13:15
 */
public class DateTimeFormatValidate implements AnnotationValidate {

    @Override
    public boolean support(Class annotationClass) {
        return XumDateTimeFormat.class.equals(annotationClass);
    }

    @Override
    public ValidateError valid(Annotation annotation, Field field, Object obj, Object value, AnnotationCacheValidate handler) {
        XumDateTimeFormat a = (XumDateTimeFormat) annotation;
        boolean isNull = (value == null || (value instanceof String && "".equals(value)));
        if (isNull) {
            return null;
        }
        String[] splitValues = a.value();
        if (splitValues.length == 0) {
            splitValues = new String[]{"-", ":"};
        }
        if (!(splitValues.length == 1 || splitValues.length == 2 || splitValues.length == 4)) {
            throw new XumValidException("XumDateTimeFormat value值长度为1,2,4");
        }
        String[] split = new String[4];
        switch (splitValues.length) {
            case 1:
                for (int i = 0; i < 4; i++) {
                    split[i] = splitValues[0];
                }
                break;
            case 2:
                for (int i = 0; i < 4; i++) {
                    split[i] = splitValues[i / 2];
                }
                break;
            case 4:
                split = splitValues;
                break;
            default:
                throw new XumValidException("XumDateTimeFormat value值长度为1,2,4");
        }
        String regex = "^" + a.startWith() + "([0-9]{4})" + split[0] + "((0[1-9])|(1[0-2]))" + split[1] +
                "((0[1-9])|([1-2][0-9])|(3[0-1]))" + a.split() +
                (a.hourType() == HourType.H24 ? "(([0-1][0-9])|(2[0-4]))" : "((0[0-9])|(1[0-2]))") +
                split[2] + "(([0-5][0-9])|(60))" + split[3] + "(([0-5][0-9])|(60))" + a.endWith() + "$";
        return Pattern.matches(regex, value.toString()) ? null :
                new ValidateError(getErrorMessage(a.message(), field, value));
    }

    private String getErrorMessage(String message, Field field, Object value) {
        return "".equals(message)
                ? field.getName() + "不符合要求的时间格式"
                : message.replaceAll("#value#", String.valueOf(value)).replaceAll("#name#", field.getName());
    }

}
